package io.github.jianjianghui.groot.core;

import io.github.jianjianghui.groot.core.annotation.GrootMemoryUnit;
import io.github.jianjianghui.groot.core.annotation.Idempotent;
import io.github.jianjianghui.groot.core.annotation.Validator;

import java.util.Arrays;
import java.util.Objects;

/**
 * 幂等验证器
 *
 * @author <a href="https://www.github.com/jianjianghui">Jianghui Jian<a/>
 * @date 2021/8/27 - 13:28
 */
public class GrootValidator implements Validator<Groot> {

    final GrootMemoryUnit grootMemoryUnit;

    public GrootValidator(GrootMemoryUnit grootMemoryUnit) {
        this.grootMemoryUnit = grootMemoryUnit;
    }

    @Override
    public boolean valid(Groot groot) {
        Idempotent idempotent = groot.getIdempotent();
        boolean idempotentHasNone = Arrays.stream(idempotent.accessible()).anyMatch(grootStatusEnum -> grootStatusEnum == GrootStatusEnum.NONE);
        GrootRequest grootRequest = groot.getGrootRequest();
        GrootRequest memoryGrootRequest = grootMemoryUnit.get(grootRequest.getIp(), grootRequest.getRequestId());

        boolean grootIsNull = Objects.isNull(memoryGrootRequest);
        if (idempotentHasNone && grootIsNull) {
            return false;
        }

        groot.setGrootRequest(memoryGrootRequest);
        return !groot.requestStatusExistInIdempotentAccessible();
    }
}
